<template>
  <router-link
    class="flex justify-between text-[#e54c5f]"
    to="/exchange/publish"
  >
    <div class="flex items-center cursor-pointer">
      <el-icon>
        <ArrowLeftBold />
      </el-icon>
      <p class="pl-5">{{ $t("创建挂单") }}</p>
    </div>
  </router-link>
  <el-card class="my-5">
    <div class="flex">
      <div>
        <h3 class="mb-1">{{ $t("卖出币种") }}</h3>
        <el-select
          v-model="form.sell_currency"
          :placeholder="$t('请选择卖出币种')"
          clearable
          style="width: 280px"
          size="large"
          @change="getBalance"
        >
          <el-option
            v-for="item in currencyList"
            :key="item.key"
            :label="item.name"
            :value="item.symbol"
          ></el-option>
        </el-select>
      </div>
      <div class="ml-12">
        <h3 class="mb-1">{{ $t("买入币种") }}</h3>
        <el-select
          v-model="form.buy_currency"
          :placeholder="$t('请选择买入币种')"
          clearable
          style="width: 280px"
          size="large"
        >
          <el-option
            v-for="item in currencyList"
            :key="item.key"
            :label="item.name"
            :value="item.symbol"
          ></el-option>
        </el-select>
      </div>
    </div>
    <div class="mt-5">
      <h3 class="mb-1">
        {{ $t("卖出金额") }}
        <el-text v-if="sellCurrencyBalance"
          >(可用余额：{{ sellCurrencyBalance }}
          {{ form.sell_currency }})</el-text
        >
      </h3>
      <el-input
        v-model="form.sell_amount"
        type="number"
        :placeholder="$t('卖出金额')"
        clearable
        size="large"
        style="width: 612px"
        ><template #append>{{ form.sell_currency }}</template></el-input
      >
      <p class="mt-3" v-if="form.buy_currency && form.sell_currency">
        {{ $t("参考价格") }}
        <span class="px-5">
          1 <el-text class="bg-gray-100">{{ form.sell_currency }}</el-text> ≈
          {{ exchangePrice1 }}
          <el-text class="bg-gray-100">{{ form.buy_currency }}</el-text>
        </span>
        <!--<span class="px-5">-->
        <!--    1 <el-text class="bg-gray-100">{{ form.buy_currency }}</el-text> ≈-->
        <!--    {{ exchangePrice }} <el-text class="bg-gray-100">{{ form.sell_currency }}</el-text>-->
        <!--</span>-->
      </p>
    </div>
    <div class="mt-5">
      <h3 class="mb-1">{{ $t("单笔限额") }}</h3>
      <el-input
        v-model="form.min_amount"
        type="number"
        :placeholder="$t('单笔最小金额')"
        clearable
        size="large"
        style="width: 300px"
        ><template #append>{{ form.sell_currency }}</template></el-input
      >
      -
      <el-input
        v-model="form.max_amount"
        type="number"
        :placeholder="$t('单笔最大金额')"
        clearable
        size="large"
        style="width: 300px"
        ><template #append>{{ form.sell_currency }}</template></el-input
      >
    </div>
    <div class="mt-10">
      <el-radio-group
        v-model="form.price_type"
        class="mb-5"
        @change="handleChange"
      >
        <el-radio label="fixed" size="large">{{ $t("固定价格") }}</el-radio>
        <el-radio label="float" size="large">{{ $t("浮动价格") }}</el-radio>
      </el-radio-group>
      <div>
        <el-input
          v-model="form.price"
          type="number"
          :placeholder="$t('请输入价格浮动比例')"
          :prefix-icon="Plus"
          size="large"
          style="width: 614px"
          v-if="form.price_type == 'float'"
        >
          <template #prepend v-if="form.buy_currency && form.sell_currency">
            1 {{ form.sell_currency }} ≈ {{ exchangePrice1 }}
            {{ form.buy_currency }}
          </template>
          <template #append>%</template>
        </el-input>
        <el-input
          v-model="form.price"
          type="number"
          :placeholder="$t('请输入固定价格')"
          size="large"
          style="width: 614px"
          v-else
        >
          <template #prepend v-if="form.sell_currency"
            >1 {{ form.sell_currency }} ≈</template
          >
          <template #append v-if="form.buy_currency">{{
            form.buy_currency
          }}</template>
        </el-input>
      </div>
      <div class="mt-5">
        <h3 class="mb-1">{{ $t("选择可见商户") }}</h3>
        <el-select
          v-model="form.display_mer_ids"
          multiple
          :placeholder="$t('选择可见商户')"
          style="width: 614px"
          size="large"
        >
          <el-option
            v-for="item in exMerchantsList"
            :key="item.merchant_id"
            :label="item.merchant_id + '-' + item.merchant_name"
            :value="item.merchant_id"
          />
        </el-select>
      </div>
    </div>
    <el-button
      type="primary"
      :icon="SuccessFilled"
      class="mt-10 w-52"
      size="large"
      @click="onSubmit"
    >
      {{ $t("提交") }}
    </el-button>
  </el-card>
</template>

<script setup>
import { ref, reactive, watch } from "vue";
import {
  getCurrencyNewApi,
  entPublishApi,
  exchangePriceNewApi,
  openExMerchantsApi,
} from "@/api/exchange/index";
import { getAssetsApi } from "@/api/assetDetails/index";
import { ElMessage } from "element-plus";
import { SuccessFilled, Plus } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const currencyList = ref([]); // 币种
const exMerchantsList = ref([]); // 商户
const router = useRouter();
const form = reactive({
  buy_currency: "",
  sell_currency: "",
  sell_amount: "",
  min_amount: "",
  max_amount: "",
  price_type: "",
  price: 0,
  display_mer_ids: "",
});
const exchangePrice = ref(0);
const exchangePrice1 = ref(0);
const sellCurrencyBalance = ref(0);
// 获取币种
const getCurrencyData = async () => {
  const res = await getCurrencyNewApi();
  currencyList.value = res.currency;
};
// 获取商户
const getExMerchantsData = async () => {
  const res = await openExMerchantsApi();
  exMerchantsList.value = res;
};
// 下拉框
const handleChange = (value) => {
  // console.log(value);
  form.price = value == "fixed" ? exchangePrice1.value : 0;
};
// 提交
const onSubmit = async () => {
  try {
    // 提交数据
    const res = await entPublishApi({
      ...form,
      // order_no: route.query.order_no,
    });
    ElMessage({
      showClose: true,
      message: t("成功"),
      type: "success",
    });
    router.replace(`/exchange/publish`);
  } catch (error) {}
};

// 监听 buy_currency 和 sell_currency 的变化
watch(
  [() => form.buy_currency, () => form.sell_currency],
  async ([buyCurrency, sellCurrency]) => {
    if (buyCurrency && sellCurrency) {
      // 在这里进行 exchangePriceNewApi 请求并将结果赋值给 form.price
      try {
        const response = await exchangePriceNewApi({
          buy_currency: buyCurrency,
          sell_currency: sellCurrency,
        });
        exchangePrice.value = response.price;
        exchangePrice1.value = response.price1;
      } catch (error) {
        // 处理请求错误
        console.error("Error fetching exchange price: ", error);
        exchangePrice.value = 0;
        exchangePrice1.value = 0;
      }
    } else {
      exchangePrice.value = 0;
      exchangePrice1.value = 0;
    }
  }
);
// 获取卖出币种余额
const getBalance = async (value) => {
  const res = await getAssetsApi({ currency: value });
  sellCurrencyBalance.value = res.list[0].available;
};
Promise.all([getCurrencyData(), getExMerchantsData()]);
</script>
